package com.zjw.zy.base.special;

import java.util.HashSet;
import java.util.Set;

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/7/19 13:13
 * <p>
 * 标记可执行状态下任务池
 */
public final class ActiveTaskPool {

    private static final String TAG = "ActiveTaskPool";

    private volatile boolean isActive = false;

    private final Set<Runnable> mTaskPools = new HashSet<>();

    public ActiveTaskPool() {

    }

    public void doIgnoreActive() {
        synchronized (this) {
            run();
        }
    }

    public void active() {
        synchronized (this) {
            isActive = true;
            run();
        }
    }


    public void unActive() {
        synchronized (this) {
            isActive = false;
        }
    }

    public void post(Runnable task) {
        synchronized (this) {
            if (isActive) {
                task.run();
                return;
            }
            mTaskPools.add(task);
        }
    }

    private void run() {
        for (Runnable task : mTaskPools) {
            task.run();
        }
        mTaskPools.clear();
    }

    public void clear() {
        synchronized (this) {
            mTaskPools.clear();
        }
    }
}
